文章目录
思路文件夹结构递归+遍历读取想要的文件
思路
首先遍历父文件夹下所有内容,如果内容是文件+【其他条件,如读取PDF,Excel】则直接读取,不是文件则递归重复上一步操作。
文件夹结构
话不多说,上菜!先给大家展示一下文件结构如下:
实现代码如下:
print(os.getcwd().rsplit('\\')[-1])
for i in os.listdir(os.getcwd()):
if os.path.isdir(i):
print('\t{}'.format(i))
for file in os.listdir(i):
print('\t\t',file)
else:
print(i)
递归+遍历读取想要的文件
用一个dataframe记录,文件名和对应内容,最终结果如下: 对应代码如下:
import os
import docx
import pandas as pd
def read_word(cur_dir):
for sub_file in os.listdir(cur_dir):
# 遍历该文件夹下所有内容,可能有各自文件或者文件夹
sub_file_abs_path = os.path.join(cur_dir, sub_file) # 拼为完整路径,方便后面使用
if os.path.isfile(sub_file_abs_path):
# 判断是否为文件, 如果是文件,拼接完整path
file_path = os.path.join(cur_dir, sub_file)
if file_path.rsplit('.')[-1] == 'docx':
# 判断是否是docx文件
fp = docx.Document(file_path)
content = ""
for p in fp.paragraphs:
content += p.text
data.loc[len(data)] = [file_path.rsplit('\\')[-1], content]
else:
sub_folder_path = os.path.join(cur_dir, sub_file)
read_word(sub_folder_path)
友情提示:博主也是学习路上的一员,代码可能不是最优最简洁,但亲测有效。如果读者觉得有帮助则借鉴,可以完善的地方希望能多多指教一起学习。思路来源感谢Allan。
|